package com.sec.android.app.myfiles.facade.cmd;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.facade.MyFilesFacade;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment.ActionModeType;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.info.FileType;
import com.sec.android.app.myfiles.info.MediaFile;
import com.sec.android.app.myfiles.info.MimeType;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.log.SamsungAnalyticsLog;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.local.file.LocalFileRecord;
import com.sec.android.app.myfiles.util.BixbyUtil;
import com.sec.android.app.myfiles.util.DrmUtils;
import com.sec.android.app.myfiles.util.FileUtils;
import com.sec.android.app.myfiles.util.SemFwWrapper;
import com.sec.android.app.myfiles.util.StorageMonitor;
import com.sec.android.app.myfiles.util.UiUtils;

import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.command.SimpleCommand;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;


public class ShareViaCmd extends SimpleCommand {
    private static final String EASY_SHARE_MORE_QUICK_CONNECT = "more_actions_quick_connect";
    private static final String ACTION_FOLDER_SHARE_VIA_WIFI = "com.samsung.android.allshare.service.fileshare.FOLDER_SEND";

    private AbsMyFilesFragment mFragment;
    private Context mContext;
    private String mAppListFromEm;
    private boolean mShowProgress;

    private final BlockingQueue<Runnable> mLoadQueue = new LinkedBlockingQueue<>();
    private final ThreadPoolExecutor mLoadThreadPool = new ThreadPoolExecutor(
            AppConstants.NUMBER_OF_THREADS, AppConstants.NUMBER_OF_THREADS,
            AppConstants.IDLE_THREAD_KEEP_ALIVE_TIME, AppConstants.IDLE_THREAD_KEEP_ALIVE_TIME_UNIT,
            mLoadQueue);

    @Override
    public void execute(INotification notification) {
        Object[] params = (Object[]) notification.getBody();

        mContext = (Context) params[0];
        mFragment = (AbsMyFilesFragment) params[1];
        @SuppressWarnings("unchecked")
        ArrayList<FileRecord> recordList = (ArrayList<FileRecord>) params[2];
        boolean isFromConvert = (Boolean) params[3];
        mAppListFromEm = (String) params[4];
        mShowProgress = (Boolean) params[5];

        if (recordList == null || recordList.isEmpty()) {
            mFragment.setActionMode(ActionModeType.SELECT_SHARE_FILE_OPERATION);
        } else {
            int sourceType = FileUtils.getRecordType(recordList);
            if (sourceType == FileUtils.ITEM_TYPE.FILE) {
                startShare(recordList, isFromConvert);
            } else {
                int message;
                if (sourceType == FileUtils.ITEM_TYPE.FILE_AND_FOLDER) {
                    message = AppFeatures.isChinaModel() ? R.string.share_files_and_folders_chn : R.string.share_files_and_folders;
                } else {
                    message = AppFeatures.isChinaModel() ? R.string.share_folders_only_chn : R.string.share_folders_only;
                }
                showDialog(message, sourceType, recordList, isFromConvert);
            }
        }
    }

    private void showDialog(int message, final int sourceType, final ArrayList<FileRecord> recordList, final boolean isFromConvert) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(AppFeatures.isChinaModel() ? R.string.share_via_wlan_direct_header : R.string.share_via_wifi_direct_header);
        builder.setMessage(message)
                .setPositiveButton(AppFeatures.isChinaModel() ? R.string.share_via_wlan_direct : R.string.share_via_wifi_direct, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        startShareViaWifiDirect(recordList, sourceType);
                        SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.SHARE_FOLDER_AND_FILES_POPUP, SamsungAnalyticsLog.Event.SHARE_USING_WIFI_DIRECT, null);
                    }
                });
        if (sourceType == FileUtils.ITEM_TYPE.FILE_AND_FOLDER) {
            builder.setNegativeButton(R.string.share_files_only, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    startShare(recordList, isFromConvert);
                    SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.SHARE_FOLDER_AND_FILES_POPUP, SamsungAnalyticsLog.Event.SHARE_FILES_ONLY, null);
                }
            }).setNeutralButton(R.string.capital_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.SHARE_FOLDER_AND_FILES_POPUP, SamsungAnalyticsLog.Event.SHARE_CANCEL, null);
                }
            });
        } else {
            builder.setNegativeButton(R.string.capital_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.SHARE_FOLDER_AND_FILES_POPUP, SamsungAnalyticsLog.Event.SHARE_CANCEL, null);
                }
            });
        }
        AlertDialog dialog = builder.create();
        ShareViaReceiver receiver = new ShareViaReceiver(mFragment.getProcessId());
        LocalBroadcastManager.getInstance(mContext).registerReceiver(receiver,
                new IntentFilter(AppConstants.DISMISS_DIALOG));
        dialog.setOnShowListener(receiver);
        dialog.show();
    }

    private void startShareViaWifiDirect(final ArrayList<FileRecord> recordList, int sourceType) {
        mFragment.finishActionMode();
        mFragment.clearListViewPreValue();

        new StartShareTask(recordList, mContext, mFragment, mLoadThreadPool, sourceType).execute();
    }

    private static LinkedList<File> getFiles(List<FileRecord> fileRecords) {
        LinkedList<File> files = new LinkedList<>();
        for (FileRecord fileRecord : fileRecords) {
            if (fileRecord != null) {
                files.add(SemFwWrapper.file(fileRecord.getFullPath()));
            }
        }
        return files;
    }

    private void startShare(ArrayList<FileRecord> recordList, boolean isFromConvert) {
        if (recordList != null) {
            int size = recordList.size();
            if (size > AppConstants.SELECT_LIMIT_COUNT) {
                Toast.makeText(mContext, mContext.getString(R.string.max_num_selected_files, AppConstants.SELECT_LIMIT_COUNT), Toast.LENGTH_SHORT)
                        .show();
                return;
            }

            mFragment.finishActionMode();
            mFragment.clearListViewPreValue();

            switch (size) {
                case 1:
                    FileRecord record = recordList.get(0);
                    if (record != null) {
                        if (needConvertToShare(mContext, record, isFromConvert)) {
                            MyFilesFacade.convert(mFragment.getProcessId(), mFragment, record);
                        } else {
                            executeShare(recordList);
                        }
                    } else {
                        mFragment.finishActionMode();
                        mFragment.clearListViewPreValue();
                    }
                    break;
                default:
                    executeShare(recordList);
                    break;
            }
        }
    }

    private void executeShare(final ArrayList<FileRecord> recordList) {
        new ExecuteShareTask(recordList, mFragment, mContext, mAppListFromEm, mLoadThreadPool, mShowProgress).execute();
    }

    private static <T> ArrayList<T> getAllResults(List<Future<T>> futures) {
        ArrayList<T> ret = new ArrayList<>(futures.size());
        for (Future<T> future : futures) {
            try {
                ret.add(future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    private static Callable<Uri> getPickUriCallable(final Context context, final String path) {
        return new Callable<Uri>() {
            @Override
            public Uri call() {
                return FileUtils.getPickUriByPath(context, path);
            }
        };
    }

    private boolean needConvertToShare(Context context, FileRecord record, boolean isFromConvert) {
        boolean needConvert = !isFromConvert;
        String path = record.getFullPath();
        String mimeType = record.getMimeType(context);
        if (needConvert) {
            if (path != null) {
                File file = SemFwWrapper.file(path);
                if (!file.exists() || !mimeType.startsWith(MimeType.IMAGE_CONTENTS)) {
                    needConvert = false;
                }
            } else {
                needConvert = false;
            }

            if (needConvert) {
                mFragment.stopObserver();
                if (mimeType.startsWith(MimeType.IMAGE_CONTENTS)
                        && !(isGolfShot(mimeType) || isSoundAndShot(mimeType, path) || isVirtualTourShot(mimeType, path))) {
                    needConvert = false;
                }
                mFragment.startObserver();
            }
        }

        return needConvert;
    }

    private boolean isGolfShot(String mimeType) {
        return (MimeType.IMAGE_GOLF).equalsIgnoreCase(mimeType);
    }

    private boolean isSoundAndShot(String mimeType, String path) {
        boolean bRet = false;
        if ((MimeType.IMAGE_JPG.equalsIgnoreCase(mimeType))) {
            File file = SemFwWrapper.file(path);
            try {
                bRet = isAudioJPEG(file);
            } catch (Exception e) {
                Log.e(this, "IOException:" + e.toString());
            }
        }

        return bRet;
    }

    private boolean isVirtualTourShot(String mimeType, String path) {
        boolean bRet = false;
        if ((MimeType.IMAGE_JPG).equalsIgnoreCase(mimeType)) {
            File file = SemFwWrapper.file(path);
        }

        return bRet;
    }

    private boolean isAudioJPEG(File file) {
        //TODO HYL 判断图片格式
        boolean bRet = false;
        return bRet;
    }

    private static class UriObserver {
        private Context mContext;

        private final int AUDIO = 0;
        private final int VIDEO = 1;
        private final int IMAGE = 2;
        private final int OTHER = 3;
        private final int TYPE_NUM = 4;

        private final int MAX_ROWS_COUNT = 999;

        Uri[] uri = {
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                FileUtils.MEDIA_PROVIDER_URI
        };

        private UriObserver(Context context) {
            mContext = context;
        }

        private String getQuestionMarkString(int elements) {
            StringBuilder sb = new StringBuilder();
            if (elements != 0) sb.append("(?");
            for (int i = 1; i < elements; i++) {
                sb.append(",?");
            }
            sb.append(")");
            return sb.toString();
        }

        private ArrayList<Uri> getUriList(ArrayList<FileRecord> recordList) {

            List<File> files = new ArrayList<>();
            setShareFiles(recordList, files);

            List<ArrayList<String>> shareFilePathList = new ArrayList<>();
            setPathListByFileType(files, shareFilePathList);

            ContentResolver cr = mContext.getContentResolver();

            ArrayList<Uri> result = new ArrayList<>();
            for (int type = 0; type < TYPE_NUM; type++) {
                Uri mediaUri = uri[type];
                List<String> shareFilePathListByType = shareFilePathList.get(type);

              /* Splitting arrays into parts with size MAX_ROWS_COUNT */
                for (int i = 0; ((i * MAX_ROWS_COUNT) < shareFilePathListByType.size()); i++) {
                    int beginIndex = i * MAX_ROWS_COUNT;
                    int endIndex = (i + 1) * MAX_ROWS_COUNT > shareFilePathListByType.size() ? shareFilePathListByType.size() : (i + 1) * MAX_ROWS_COUNT;
                    List<String> pathList = shareFilePathListByType.subList(beginIndex, endIndex);
                    String[] filePaths = pathList.toArray(new String[endIndex - beginIndex]);
                    String questionMarkString = getQuestionMarkString(filePaths.length);

                    try (Cursor c = cr.query(mediaUri, new String[]{MediaStore.MediaColumns._ID, MediaStore.MediaColumns.DATA},
                            MediaStore.MediaColumns.DATA + " IN " + questionMarkString + " COLLATE LOCALIZED", filePaths, null)) {
                        final int idColumnIndex = 0;
                        final int pathColumnIndex = 1;
                        if (c != null && c.moveToFirst()) {
                            do {
                                Uri u = UiUtils.addUserIdToUri(ContentUris.withAppendedId(mediaUri, c.getLong(idColumnIndex)));
                                result.add(u);
                                pathList.remove(c.getString(pathColumnIndex));
                            } while (c.moveToNext());
                        }
                    }

                    if (!pathList.isEmpty()) {
                        for (String path : pathList) {
                            result.add(FileUtils.getContentUri(mContext, path));
                        }
                    }
                }
            }
            return result;
        }

        private void setPathListByFileType(List<File> files, List<ArrayList<String>> shareFilePathList) {
            initPathList(shareFilePathList);

            String path;
            for (File file : files) {
                path = file.getAbsolutePath();
                int fileType = MediaFile.getFileType(path);
                boolean isForwardable = true;
                if (FileType.isPlayReadyType(fileType) || FileType.isDrmFileType(fileType)) {
                    isForwardable = DrmUtils.isForwardable(mContext, path);
                }

                boolean added = true;

                if (isForwardable) {
                    fileType = MediaFile.getFileTypeForMimeType(MediaFile.getMimeType(mContext, path));
                    if (!FileUtils.hasMediaScanSkipPath(path)) {
                        if (FileType.isAudioFileType(fileType)) {
                            shareFilePathList.get(AUDIO).add(path);
                        } else if (FileType.isVideoFileType(fileType)) {
                            shareFilePathList.get(VIDEO).add(path);
                        } else if (FileType.isImageFileType(fileType)) {
                            shareFilePathList.get(IMAGE).add(path);
                        } else {
                            added = false;
                        }
                    } else added = false;
                    if (!added && !SemFwWrapper.file(path).isDirectory()) {
                        shareFilePathList.get(OTHER).add(path);
                    }
                }
            }
        }

        private void initPathList(List<ArrayList<String>> pathList) {
            for (int i = 0; i < 4; i++) {
                pathList.add(new ArrayList<String>());
            }
        }

        private void setShareFiles(ArrayList<FileRecord> recordList, List<File> files) {
            LinkedList<File> fileList = getFiles(recordList);
            while (!fileList.isEmpty()) {
                final File localFile = fileList.removeFirst();
                 /* For Sub Directory */
                if (localFile.isDirectory()) {
                    fileList.addAll(Arrays.asList(localFile.listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            return (file.length() > 0);
                        }
                    })));
                } else {
                    files.add(localFile);
                }
            }
        }
    }

    private static class StartShareTask extends AsyncTask<Void, Void, ArrayList<Uri>> {
        ArrayList<FileRecord> mRecordList;
        Context mContext;
        AbsMyFilesFragment mFragment;
        ThreadPoolExecutor mLoadThreadPool;
        int mSourceType;

        public StartShareTask(ArrayList<FileRecord> recordList, Context context, AbsMyFilesFragment fragment, ThreadPoolExecutor loadThreadPool, int sourceType) {
            mRecordList = recordList;
            mContext = context;
            mFragment = fragment;
            mLoadThreadPool = loadThreadPool;
            mSourceType = sourceType;
        }

        @Override
        protected void onPreExecute() {
            MyFilesFacade.execSpinnerProgress(mFragment.getProcessId(), mContext, SpinnerProgressCmd.OperationProgress.SHOW);
        }

        @Override
        protected void onPostExecute(ArrayList<Uri> uris) {
            if (uris != null && uris.size() > AppConstants.SELECT_LIMIT_COUNT) {
                MyFilesFacade.execSpinnerProgress(mFragment.getProcessId(), mContext, SpinnerProgressCmd.OperationProgress.DISMISS);
                Toast.makeText(mContext, mContext.getString(R.string.max_num_selected_files, AppConstants.SELECT_LIMIT_COUNT), Toast.LENGTH_SHORT)
                        .show();
            } else if (uris != null && uris.size() > 0) {
                Intent intent = new Intent(ACTION_FOLDER_SHARE_VIA_WIFI);
                intent.setType("application/*");
                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
                intent.putExtra(AppConstants.INTENT_KEY_PARENT_FOLDER, mRecordList.get(0).getPath());
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                MyFilesFacade.execSpinnerProgress(mFragment.getProcessId(), mContext, SpinnerProgressCmd.OperationProgress.DISMISS);
                if (!mContext.getPackageManager().queryIntentActivities(intent, 0).isEmpty()) {
                    mContext.startActivity(intent);
                } else {
                    Log.e(this, "No Activities for Wifi direct folder share");
                }
            } else {
                MyFilesFacade.execSpinnerProgress(mFragment.getProcessId(), mContext, SpinnerProgressCmd.OperationProgress.DISMISS);
                Toast.makeText(mContext, mContext.getResources()
                        .getQuantityString(R.plurals.n_empty_folder_cannot_share_via_wifi_direct, mRecordList.size(), mRecordList.size()), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        protected ArrayList<Uri> doInBackground(Void... params) {
            if (mSourceType == FileUtils.ITEM_TYPE.CATEGORY_FOLDER) {
                mRecordList = FileUtils.getCategoryFolderRecordList(null, mRecordList);
            }
            if (mRecordList != null && !mRecordList.isEmpty()) {
                if (StorageMonitor.startWithUsbRoot(mRecordList.get(0).getFullPath())) {
                    return getAllFileList(mRecordList);
                } else {
                    return new UriObserver(mContext).getUriList(mRecordList);
                }
            }
            return null;
        }

        private ArrayList<Uri> getAllFileList(ArrayList<FileRecord> recordList) {
            LinkedList<File> fileList = getFiles(recordList);
            List<Future<Uri>> futures = new ArrayList<>(fileList.size());
            while (!fileList.isEmpty()) {
                final File localFile = fileList.removeFirst();
                if (localFile.isDirectory()) {
                    fileList.addAll(Arrays.asList(localFile.listFiles()));
                } else {
                    int fileType = MediaFile.getFileType(localFile.getAbsolutePath());
                    boolean isFowardable = true;
                    if (FileType.isPlayReadyType(fileType) || FileType.isDrmFileType(fileType)) {
                        isFowardable = DrmUtils.isForwardable(mContext, localFile.getAbsolutePath());
                    }

                    if (isFowardable) {
                        futures.add(mLoadThreadPool.submit(getPickUriCallable(mContext, localFile.getAbsolutePath())));
                    }
                }
            }

            return getAllResults(futures);
        }

    }

    private static class ExecuteShareTask extends AsyncTask<Void, Void, Intent> {
        ArrayList<FileRecord> mRecordList;
        AbsMyFilesFragment mFragment;
        Context mContext;
        ThreadPoolExecutor mLoadThreadPool;
        String mAppListEm;
        boolean mShowProgress;

        public ExecuteShareTask(ArrayList<FileRecord> recordList, AbsMyFilesFragment fragment, Context context, String appList, ThreadPoolExecutor loadThreadPool, boolean isShowProgress) {
            mRecordList = recordList;
            mContext = context;
            mFragment = fragment;
            mLoadThreadPool = loadThreadPool;
            mAppListEm = appList;
            mShowProgress = isShowProgress;
        }

        @Override
        protected void onPreExecute() {
            if (mShowProgress) {
                MyFilesFacade.execSpinnerProgress(mFragment.getProcessId(), mContext, SpinnerProgressCmd.OperationProgress.SHOW);
            }
        }

        @Override
        protected void onPostExecute(Intent intent) {
            if (mShowProgress) {
                MyFilesFacade.execSpinnerProgress(mFragment.getProcessId(), mContext, SpinnerProgressCmd.OperationProgress.DISMISS);
            }
            if (intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM) != null &&
                    intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM).size() > AppConstants.SELECT_LIMIT_COUNT) {
                Toast.makeText(mContext, mContext.getString(R.string.max_num_selected_files, AppConstants.SELECT_LIMIT_COUNT), Toast.LENGTH_SHORT)
                        .show();
                return;
            }

            Intent chooserIntent;
            if (mAppListEm != null) {
                chooserIntent = Intent.createChooser(intent, null);
                chooserIntent.putExtra("extra_chooser_bixby_applist", mAppListEm);
                BixbyUtil.setNestingCallerAppName(chooserIntent);
            } else {
                chooserIntent = Intent.createChooser(intent, mContext.getResources().getString(R.string.share_sheet_title));
            }

            Activity activity = mFragment.getActivity();
            if (activity != null) {
                activity.startActivity(chooserIntent);
            }
        }

        @Override
        protected Intent doInBackground(Void... params) {
            Intent intent;
            if (mRecordList.size() > 1) {
                intent = getIntentForFileList(mContext, mRecordList);
            } else {
                intent = getIntentForFile(mContext, mRecordList.get(0));
            }
            return intent;
        }

        private Intent getIntentForFile(Context context, FileRecord record) {
            String fileMimeType = record.getMimeType(context);

            if (fileMimeType != null) {
                if ((MimeType.TEXT_FILE).equalsIgnoreCase(fileMimeType) && record.getExt().equalsIgnoreCase("txt")) {
                    fileMimeType = MimeType.DOCUMENT_CONTENTS;
                } else if (fileMimeType.startsWith(MimeType.IMAGE_CONTENTS)) {
                    fileMimeType = MimeType.IMAGE_CONTENTS + "*";
                } else if (fileMimeType.contains(MimeType.SEC_FILE)) {
                    fileMimeType = MimeType.SEC_CONTENTS;
                } else if (!fileMimeType.contains("/")) {
                    fileMimeType = MediaFile.getMimeType(context, record.getFullPath());
                }
            }

            Intent ret = new Intent(Intent.ACTION_SEND);
            ret.setType(fileMimeType);
            ret.putExtra(Intent.EXTRA_STREAM, FileUtils.getUriByPath(context, record.getFullPath()));

            if (AppFeatures.isInstalledQuickConnect(context)) {
                ret.putExtra(EASY_SHARE_MORE_QUICK_CONNECT, 1);
            }

            ret.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            ret.putExtra(AppConstants.INTENT_FROM_MYFILES, true);
            return ret;
        }

        private Intent getIntentForFileList(Context context, ArrayList<FileRecord> recordList) {
            ArrayList<Uri> uriList = new UriObserver(context).getUriList(recordList);
            updateLocalFileMediaId(context, recordList);

            Intent ret = new Intent(Intent.ACTION_SEND_MULTIPLE);
            ret.setType(getCommonMimeType(context, recordList));
            ret.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriList);
            if (AppFeatures.isInstalledQuickConnect(context)) {
                ret.putExtra(EASY_SHARE_MORE_QUICK_CONNECT, 1);
            }

            ret.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            ret.putExtra(AppConstants.INTENT_FROM_MYFILES, true);
            return ret;
        }

        private void updateLocalFileMediaId(Context context, ArrayList<FileRecord> recordList) {
            if (!recordList.isEmpty()) {
                LocalFileRecord.updateMediaId(context, recordList);
            }
        }

        private String getCommonMimeType(Context context, ArrayList<FileRecord> recordList) {
            String fileMimeType;
            String commonMimeType = null;
            boolean isCheckedMimeType = true;
            boolean isOtherFile = false;
            for (FileRecord record : recordList) {
                fileMimeType = record.getMimeType(context);

                if (isCheckedMimeType) {
                    if (MimeType.TEXT_FILE.equalsIgnoreCase(fileMimeType) && record.getExt().equalsIgnoreCase("TXT")) {
                        fileMimeType = MimeType.DOCUMENT_CONTENTS;
                    }
                    commonMimeType = MediaFile.getCommonShareMimeType(fileMimeType, commonMimeType);
                    if (MimeType.ALL_CONTENTS.equals(commonMimeType)) {
                        isCheckedMimeType = false;
                    }
                }
                if (!isOtherFile) {
                    isOtherFile = record.isOtherFileType();
                }
            }
            return commonMimeType;
        }
    }

    private class ShareViaReceiver extends BroadcastReceiver implements DialogInterface.OnShowListener {

        private WeakReference<DialogInterface> mInstanceRef;
        private int mProcessId;

        public ShareViaReceiver(int processId) {
            mProcessId = processId;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            DialogInterface dialog = mInstanceRef.get();
            if (dialog != null) {
                int targetProcessId = intent.getIntExtra(AppConstants.EXTRA_PROCESS_ID, -1);
                if (targetProcessId == mProcessId) {
                    dialog.dismiss();
                }
            }
            LocalBroadcastManager.getInstance(context).unregisterReceiver(this);
        }

        @Override
        public void onShow(DialogInterface dialog) {
            mInstanceRef = new WeakReference<>(dialog);
        }
    }
}
